package com.demo.gateway.filter;

import com.alibaba.nacos.shaded.com.google.common.base.Strings;
import com.demo.common.base.constant.SysSymbolConstant;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * StripPrefix全局过滤器
 *
 * @author DayDayUp
 * create on 2023-07-14
 **/
@Component
public class GlobalStripPrefixFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest().mutate().build();
        String rawPath = request.getURI().getRawPath();
        String[] rawPathArr = StringUtils.tokenizeToStringArray(rawPath, SysSymbolConstant.SLASH);

        int length = (SysSymbolConstant.SLASH + rawPathArr[0]).length();
        String newPath = rawPath.substring(length);
        ServerHttpRequest newRequest = request.mutate().path(newPath).build();
        exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
        return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build());
    }

    @Override
    public int getOrder() {
        return -999;
    }
}
